package com.heima.search.listen;

import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private ArticleSearchService articleSearchService;

    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void handleUpMsg(String articleId){
        log.info("接收到文章上架消息 id{}" + articleId);
        System.out.println(articleId);
        ResponseResult<SearchArticleVO> responseResult = articleFeign.findArticle(Long.valueOf(articleId));
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"远程调用失败。。。。");
        }
        SearchArticleVO searchArticleVO = responseResult.getData();
        //调用索引库保存的方法
        articleSearchService.saveArticle(searchArticleVO);
        log.info("文章已添加到es索引库 id{}" + articleId);
    }

    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void handleDownMsg(String articleId){
        log.info("接收到文章下架消息id{}" + articleId);
        articleSearchService.deleteArticle(articleId);
        log.info("文章已从es索引库删除 id{}" + articleId);
    }
}
